import json
import components.Regex
import components.NFA
import components.DFA

def loadRegex():
    with open('param/regex.json') as loadFile:
        result = {}
        loadDict = json.load(loadFile)
        loadList = loadDict.items()
        for t in loadList:
            # print components.Regex.regexInfixToPostfix(components.Regex.regexAddConcatOps(str(t[1])))
            if str(t[0]) == 'operator':
                result[str(t[0])] = regex2DFA('+++&|+=&|-|--&|-=&|//&|<|<=&|>|>=&|=|==&|!=&|^|#|%|~|<<&|>>&|\|.|:|!|')
            else:
                result[str(t[0])] = regex2DFA(components.Regex.regexInfixToPostfix(components.Regex.regexAddConcatOps(str(t[1]))))
            result[str(t[0])].name = str(t[0])
            # print result[str(t[0])].name
            # print result[str(t[0])].endStates
    return result

def regex2DFA(regex):
    i = 0
    stack = []
    while i < len(regex):
        if regex[i] == '/':
            n = components.NFA.NFA('/'+regex[i+1], 0)
            stack.append(n)
            i += 3
        elif regex[i] == '&':
            b = stack.pop()
            a = stack.pop()
            stack.append(a.seriesConnection(b))
            i += 1
        elif regex[i] == '*':
            a = stack.pop()
            stack.append(a.circuitConnection())
            i += 1
        elif regex[i] == '|':
            b = stack.pop()
            a = stack.pop()
            stack.append(a.parallelConnection(b))
            i += 1
        else:
            n = components.NFA.NFA(regex[i], 0)
            stack.append(n)
            i += 1
    nfa = stack.pop()
    nfa.fomalize()
    return components.DFA.DFA(nfa)

if __name__ == "__main__":
    s = loadRegex()
    s['operator'].showTransferTable()